package com.esyoga.yoyoga.handler;

import com.esyoga.yoyoga.pojo.*;
import com.esyoga.yoyoga.pojo.DTO.GymAgreementDTO;
import com.esyoga.yoyoga.pojo.DTO.GymOrdersDTO;
import com.esyoga.yoyoga.pojo.DTO.PlatformContractDTO;
import com.esyoga.yoyoga.pojo.DTO.TrainerWithStarDTO;
import com.esyoga.yoyoga.service.GymService;
import com.esyoga.yoyoga.service.GymVerifyService;
import com.esyoga.yoyoga.service.PlatformService;
import com.esyoga.yoyoga.util.CutPagesUtil;
import com.esyoga.yoyoga.util.PictureInvertUtil;
import lombok.Data;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Data
@Controller
@RequestMapping("/platForm")
public class PlatformHandler {

    @Resource
    private PlatformService platformService;
    @Resource
    private GymService gymService;
    @Resource
    private GymVerifyService gymVerifyService;

    private Map<String, Object> result = new HashMap<>();

    /*与场馆解约*/
    @RequestMapping("/rescissionWithGym")
    @ResponseBody
    public void rescissionWithGym(int gid){
        platformService.rescissionWithGym(gid);
    }

    /*展示所有未审核的场馆签约请求*/
    @RequestMapping("/findGymSignRequest")
    @ResponseBody
    public Map<String, Object> findGymSignRequest(int page){
        List<GymAgreementDTO> gymAgreementDTOS=platformService.findGymAgreementsByState();
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<GymAgreementDTO> tGymAgreementList = CutPagesUtil.getPages(gymAgreementDTOS);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tGymAgreementList);
        result.put("total",totalPage);
        return result;
    }

    /*场馆签约*/
    @RequestMapping("/GymContract")
    @ResponseBody
    public String GymContract(int gaid, int flag){
        return platformService.GymContract(gaid, flag);
    }

    /*添加场馆*/
    @RequestMapping("/addGym")
    @ResponseBody
    public String addGym(TGym tGym, @RequestParam MultipartFile[] file, HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
        //判断是不是一个重复账号
        if(gymVerifyService.findTGymPasswordByPhone(tGym.getgAccount())!=null){
            return "已有此场馆账号";
        }
        //1.将文件保存到Tomcat服务器本地
        //1.1.获取保存文件的文件夹的路径
        String path =  request.getServletContext().getRealPath("/image");
        File dir = new File(path);
        //获得webapp文件夹的file对象
        File webapp = dir.getParentFile();
        //获取/创建image文件夹
        File image = new File(webapp, "image");
        if (!image.exists()) {
            image.mkdirs();//创建文件夹
        }
        List<String> imgsName=new ArrayList<>();
        for (MultipartFile f:file) {
            String fileName = f.getOriginalFilename();
            //生成新文件名
            String newName = UUID.randomUUID().toString();
            //得到文件后缀名
            String type = fileName.substring(fileName.lastIndexOf("."));
            //
            newName+=type;
            //拼接新文件的路径
            imgsName.add(newName);
            File uploadFile  = new File(image,newName);
            //1.2.将文件保存到服务器本地
            f.transferTo(uploadFile);
        }
        //2.1.获取文件的路径（相对路径），将所有的注册信息保存到数据库
        tGym.setgImage(PictureInvertUtil.getPathsString(imgsName));
        platformService.addGym(tGym);
//        System.out.println("执行前");
//        request.getRequestDispatcher("/html/platform.html").forward(request,response);
//        response.sendRedirect("/html/platform.html");
//        System.out.println("执行后");
        return "添加成功";
    }

    /*教练审核*/
    @RequestMapping("/trainerAudit")
    @ResponseBody
    public void trainerAudit(int tid, int flag){
        platformService.trainerAudit(tid, flag);
    }

    /*教练禁用*/
    @RequestMapping("/trainerBan")
    @ResponseBody
    public void trainerBan(int tid){
        platformService.trainerBan(tid);
    }

    /*教练解封*/
    @RequestMapping("/trainerUnblocked")
    @ResponseBody
    public void trainerUnblocked(int tid){
        platformService.trainerUnblocked(tid);
    }

    /*展示所有场馆*/
    @RequestMapping("/findGyms")
    @ResponseBody
    public Map<String, Object> findGyms(int page){
        List<TGym> tGyms=platformService.findGyms();
        List<TGym> nowGyms=new ArrayList<>();
        //场馆可能会有多张照片，选择第一张照片展示
        for (TGym gym:tGyms) {
            String imgs=gym.getgImage();
            String[] strs = imgs.split(";");
            gym.setgImage(strs[0]);
            nowGyms.add(gym);
        }
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TGym> tGymList = CutPagesUtil.getPages(nowGyms);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tGymList);
        result.put("total",totalPage);
        return result;
    }

    /*展示所有已签约场馆*/
    @RequestMapping("/findGymsByStateZero")
    @ResponseBody
    public Map<String, Object> findGymsByStateZero(int page){
        List<TGym> tGyms=platformService.findGymsByStateZero();
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TGym> tGymList = CutPagesUtil.getPages(tGyms);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tGymList);
        result.put("total",totalPage);
        return result;
    }

    /*展示所有教练*/
    @RequestMapping("/findTrainers")
    @ResponseBody
    public Map<String, Object> findTrainers(int page){
        List<TTrainer> tTrainers=platformService.findTrainers();
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TTrainer> tTrainersList = CutPagesUtil.getPages(tTrainers);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tTrainersList);
        result.put("total",totalPage);
        return result;
    }

    /*展示所有认证教练*/
    @RequestMapping("/findTrainersByStateOne")
    @ResponseBody
    public Map<String, Object> findTrainersByStateOne(int page){
        List<TTrainer> tTrainers=platformService.findTrainersByStateOne();
        List<TrainerWithStarDTO> trainerWithStarDTOS=new ArrayList<>();
        for (TTrainer t:tTrainers) {
            BigDecimal star=gymService.countStarForTrainer(t.gettId());
            TrainerWithStarDTO trainerWithStarDTO=new TrainerWithStarDTO(star,t);
            trainerWithStarDTOS.add(trainerWithStarDTO);
        }
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TrainerWithStarDTO> tTrainersList = CutPagesUtil.getPages(trainerWithStarDTOS);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tTrainersList);
        result.put("total",totalPage);
        return result;
    }

    /*展示所有被禁用教练*/
    @RequestMapping("/findTrainersByStateTwo")
    @ResponseBody
    public Map<String, Object> findTrainersByStateTwo(int page){
        List<TTrainer> tTrainers=platformService.findTrainersByStateTwo();
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TTrainer> tTrainersList = CutPagesUtil.getPages(tTrainers);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tTrainersList);
        result.put("total",totalPage);
        return result;
    }

    /*展示所有未认证教练*/
    @RequestMapping("/findTrainersByStateZero")
    @ResponseBody
    public Map<String, Object> findTrainersByStateZero(int page){
        List<TTrainer> tTrainers=platformService.findTrainersByStateZero();
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TTrainer> tTrainersList = CutPagesUtil.getPages(tTrainers);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tTrainersList);
        result.put("total",totalPage);
        return result;
    }

    /*展示所有用户*/
    @RequestMapping("/findStudents")
    @ResponseBody
    public Map<String, Object> findStudents(int page){
        List<TStudent> tStudents=platformService.findStudents();
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<TStudent> tStudentList = CutPagesUtil.getPages(tStudents);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",tStudentList);
        result.put("total",totalPage);
        return result;
    }

    /*查询所有订单*/
    @RequestMapping("/findOrders")
    @ResponseBody
    public Map<String, Object> findOrders(int page){
        List<TOrder> tOrders= platformService.findOrders();
        List<GymOrdersDTO> gymOrdersDTOS=new ArrayList<>();
        for (TOrder o:tOrders) {
            TContract tContract=platformService.findContractByOid(o.getoId());
            String sname=platformService.findSnameBySid(tContract.getcSId());
            String tname=platformService.findTnameByTid(tContract.getcTId());
            GymOrdersDTO gymOrdersDTO=new GymOrdersDTO(sname,tname,o);
            gymOrdersDTOS.add(gymOrdersDTO);
        }
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<GymOrdersDTO> gymOrdersDTOSList = CutPagesUtil.getPages(gymOrdersDTOS);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",gymOrdersDTOSList);
        result.put("total",totalPage);
        return result;
    }

    /*查询所有合约*/
    @RequestMapping("/findContracts")
    @ResponseBody
    public Map<String, Object> findContracts(int page){
        List<TContract> tContracts= platformService.findTContract();
        List<PlatformContractDTO> platformContractDTOS=new ArrayList<>();
        for (TContract contract:tContracts) {
           String sname=platformService.findSnameBySid(contract.getcSId());
           String tname=platformService.findTnameByTid(contract.getcTId());
           String gname=platformService.findGnameByGid(contract.getcGId());
           PlatformContractDTO platformContractDTO=new PlatformContractDTO(sname,tname,gname,contract);
           platformContractDTOS.add(platformContractDTO);
        }
        CutPagesUtil.clear();
        CutPagesUtil.setPageInfo(page,10);
        List<PlatformContractDTO> platformContractDTOList = CutPagesUtil.getPages(platformContractDTOS);
        int totalPage = CutPagesUtil.getTotalPage();

        result.put("rows",platformContractDTOList);
        result.put("total",totalPage);
        return result;
    }

    /*根据订单id查看评价*/
    @RequestMapping("/findEvalutionByOid")
    @ResponseBody
    public TEvaluation findEvalutionByOid(int oid){
        return platformService.findEvalution(oid);
    }


    /*查余额*/
    @RequestMapping("/countBalance")
    @ResponseBody
    public BigDecimal countBalance(){
        return platformService.countBalance();
    }


    /*根据gid查某个场馆*/
    @RequestMapping("/findGymByGid")
    @ResponseBody
    public Map<String,Object> findGymByGid(int gId){
        TGym tGym=gymService.findGymByGid(gId);
        List<String> imgs=PictureInvertUtil.getPathsList(tGym.getgImage());
        Map<String,Object> gym=new HashMap<>();
        gym.put("imgs",imgs);
        gym.put("gym",tGym);
        return gym;
    }
}
